function HD (fn) {
  this.status = 'PENDING'; // ful   rej
  this.value = null;
  this.callbacks = [];
  // 错误处理
  var reject = (reason) => {
    if(this.status != 'PENDING') return this
    this.status = 'rejected'
    this.value = reason;
    setTimeout(() => {
      this.callbacks.map(callback => {
        callback.rej(reason)
      })
    })
    return this
  }
  // 成功处理
  var resolve = (value) => {
    if(this.status != 'PENDING') return this
    this.status = 'FUFILLED'
    this.value = value;
    setTimeout(() => {
      this.callbacks.map(callback => {
        callback.res(value)
      })
    })
    return this
  }
  // 回调成功
  this.then = (res, rej) => {
    if(typeof res != 'function') {
      res = () => {
        return this.value
      }
    }
    if(typeof rej != 'function') {
      rej = () => {
        return this.value
      }
    }
    if(this.status != 'FUFILLED' && this.status != 'rejected') {
      this.callbacks.push({
        res: value => {
          try {
            res(value)
          } catch (error) {
            rej(error)
          }
        }
        ,rej: value => {
          try {
            res(value)
          } catch (error) {
            rej(error)
          }
        }
      })
      return this
    }
    setTimeout(() => {
      try {
        res(this.value)
      } catch (error) {
        reject(error)
      }
    })
  }
  // 静态方法resolve与reject
  this.reject = (value) => {
    reject(value)
    return this
  }
  this.resolve = (value) => {
    resolve(value)
    return this
  }
  // 回调失败
  try {
    if(typeof fn != 'function') {
      return new HD((resolve, reject) => {
        return this
      })
    }
    fn(resolve, reject)
  } catch (error) {
    reject(error)
  }
}

// let p = new HD((resolve, reject) => {
//   // console.log(a)
//   setTimeout(() => {
//     // resolve('解决')
//     reject('没解决')
//   })
//   // reject('没解决')
// }).then((value) => {
//   console.log(value)
// },(error) => {
//   console.log('error: ' + error)
// }).then(
//   (value) => {
//     console.log(value)
//   },(error) => {
//     console.log('error: ' + error)
//   }
// )
let p = new HD()
// // console.log('aaa')
p.resolve('aaa').then((value) => {
  console.log(value)
})

// var aa = () => {
//   console.log('aa')
// }
// let Pomise = new Promise()
// Pomise.reject(aa)